<template>
	<view class="container">
		<view class="jump-container">
			<text class="jump" @click="handleJump">稍后提交</text>
		</view>
		<form @submit="handleSubmit" class="form-container">
			<!-- 基本信息区 -->
			<view class="section">
				<text class="section-title">基本信息</text>
				<!--头像-->
				<view class="form-group">
					<text class="form-label">头像</text>
					<view class="upload-wrapper" @click="chooseImage('profileImg')">
						<image 
							v-if="formData.profileImg" 
							:src="formData.profileImg" 
							class="upload-image"
							mode="aspectFill" 
						/>
						<view v-else class="upload-placeholder">
							<uni-icons type="plusempty" size="24" color="#999" />
							<text>点击上传</text>
						</view>
					</view>
				</view>
				<!--姓氏-->
				<view class="form-group">
					<text class="form-label required">姓氏</text>
					<input v-model="formData.surname" placeholder="请输入姓氏" class="form-input" :disabled="readOnly" />
				</view>
				<!--名字-->
				<view class="form-group">
					<text class="form-label required">名字</text>
					<input v-model="formData.name" placeholder="请输入名字" class="form-input" :disabled="readOnly" />
				</view>
				<!--性别-->
				<view class="form-group">
					<text class="form-label required">性别</text>
					<picker 
						mode="selector" 
						:range="sexOptions"
						@change="onChangeSex" 
						class="form-picker"
						:disabled="readOnly"
					>
						<view class="picker-content">
							<text v-if="getGenderNameByCode(formData.sex)">{{ getGenderNameByCode(formData.sex) }}</text>
							<text v-else class="please-choose">请选择性别</text>
							<uni-icons type="arrowright" size="16" color="#999" />
						</view>
					</picker>
				</view>
				<!--手机号-->
				<view class="form-group">
					<text class="form-label required">手机号</text>
					<input 
						v-model="formData.phone"
						type="number"
						class="form-input"
						maxlength="11"
						:disabled="true"
					/>
				</view>
			</view>

			<!-- 身份证信息区 -->
			<view class="section">
				<text class="section-title">身份证信息</text>
				<!--身份证号-->
				<view class="form-group">
					<text class="form-label required">身份证号</text>
					<input v-model="formData.idCard" placeholder="请输入身份证号" class="form-input" maxlength="18" :disabled="readOnly" />
				</view>
				<!--身份证正面-->
				<view class="form-group">
					<text class="form-label required">身份证正面</text>
					<view class="upload-wrapper" @click="chooseImage('idCardFrontImg')">
						<image 
							v-if="formData.idCardFrontImg" 
							:src="formData.idCardFrontImg" 
							class="upload-image"
							mode="aspectFill" 
						/>
						<view v-else class="upload-placeholder">
							<uni-icons type="plusempty" size="24" color="#999" />
							<text>点击上传</text>
						</view>
					</view>
				</view>
				<!--身份证反面-->
				<view class="form-group">
					<text class="form-label required">身份证反面</text>
					<view class="upload-wrapper" @click="chooseImage('idCardBackImg')">
						<image 
							v-if="formData.idCardBackImg" 
							:src="formData.idCardBackImg" 
							class="upload-image"
							mode="aspectFill" 
						/>
						<view v-else class="upload-placeholder">
							<uni-icons type="plusempty" size="24" color="#999" />
							<text>点击上传</text>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 紧急联系人区 -->
			<view class="section">
				<text class="section-title">紧急联系人信息</text>
				<!--紧急联系人名称-->
				<view class="form-group">
					<text class="form-label required">紧急联系人名称</text>
					<input v-model="formData.emergencyContact" placeholder="请输入紧急联系人名称" class="form-input" :disabled="readOnly" />
				</view>
				<!--紧急联系人手机号-->
				<view class="form-group">
					<text class="form-label required">紧急联系人手机号</text>
					<input 
						v-model="formData.emergencyContactPhone" 
						type="number" 
						placeholder="请输入紧急联系人手机号" 
						class="form-input"
						maxlength="11" 
						:disabled="readOnly"
					/>
				</view>
			</view>
			
			<!-- 驾照信息区 -->
			<view class="section">
				<text class="section-title">驾照信息</text>
				<!--驾驶证正面-->
				<view class="form-group">
					<text class="form-label required">驾驶证正面</text>
					<view class="upload-wrapper" @click="chooseImage('driverCardFrontImg')">
						<image 
							v-if="formData.driverCardFrontImg" 
							:src="formData.driverCardFrontImg" 
							class="upload-image"
							mode="aspectFill" 
						/>
						<view v-else class="upload-placeholder">
							<uni-icons type="plusempty" size="24" color="#999" />
							<text>点击上传</text>
						</view>
					</view>
				</view>
				<!--驾驶证反面-->
				<view class="form-group">
					<text class="form-label required">驾驶证反面</text>
					<view class="upload-wrapper" @click="chooseImage('driverCardBackImg')">
						<image 
							v-if="formData.driverCardBackImg" 
							:src="formData.driverCardBackImg" 
							class="upload-image"
							mode="aspectFill" 
						/>
						<view v-else class="upload-placeholder">
							<uni-icons type="plusempty" size="24" color="#999" />
							<text>点击上传</text>
						</view>
					</view>
				</view>
				<!--驾驶证领取时间-->
				<view class="form-group">
					<text class="form-label required">驾驶证领取时间</text>
					<picker 
						mode="date" 
						class="form-picker"
						@change="(e) => formData.driverCardReceiveTime = e.detail.value"
						:disabled="readOnly"
					>
						<view class="picker-content">
							<text v-if="formData.driverCardReceiveTime">{{ formData.driverCardReceiveTime }}</text>
							<text v-else class="please-choose">请选择日期</text>
							<uni-icons type="arrowright" size="16" color="#999" />
						</view>
					</picker>
				</view>
				<!--驾驶证到期时间-->
				<view class="form-group">
					<text class="form-label required">驾驶证到期时间</text>
					<picker 
						mode="date" 
						class="form-picker"
						@change="(e) => formData.driverCardExpriesTime = e.detail.value"
						:disabled="readOnly"
					>
						<view class="picker-content">
							<text v-if="formData.driverCardExpriesTime">{{ formData.driverCardExpriesTime }}</text>
							<text v-else class="please-choose">请选择日期</text>
							<uni-icons type="arrowright" size="16" color="#999" />
						</view>
					</picker>
				</view>
				<!--驾龄-->
				<view class="form-group">
					<text class="form-label required">驾龄(年)</text>
					<input v-model="formData.driverAge" type="number" placeholder="请输入驾龄" class="form-input" maxlength="2" :disabled="readOnly" />
				</view>
				<!--准驾车型-->
				<view class="form-group">
					<text class="form-label required">准驾车型</text>
					<picker 
						mode="selector" 
						:range="driverTypeOptions"
						@change="onChangeDriverCarType" 
						class="form-picker"
						:disabled="readOnly"
					>
						<view class="picker-content">
							<text v-if="getDriverCarNameByCode(formData.driverCarType)">{{ getDriverCarNameByCode(formData.driverCarType) }}</text>
							<text v-else class="please-choose">请选择准驾车型</text>
							<uni-icons type="arrowright" size="16" color="#999" />
						</view>
					</picker>
				</view>
			
			</view>
			
			<!-- 银行卡信息区 -->
			<view class="section">
				<text class="section-title">银行卡号信息（用于提现）</text>
				<!--开户银行-->
				<view class="form-group">
					<text class="form-label required">开户银行</text>
					<input v-model="formData.bankName" placeholder="请输入开户银行" class="form-input" :disabled="readOnly" />
				</view>
				<!--银行卡号-->
				<view class="form-group">
					<text class="form-label required">银行卡号</text>
					<input 
						v-model="formData.bankCardId" 
						type="number" 
						placeholder="请输入银行卡号" 
						class="form-input"
						maxlength="30" 
						:disabled="readOnly"
					/>
				</view>
			</view>
			
			<!-- 提交按钮 -->
			<button form-type="submit" class="submit-btn" v-if="!readOnly">
				提交信息
			</button>
		</form>
	</view>
</template>

<script setup>
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { apiUpload } from '@/api/upload.js'
import { FILE_PREFIX } from '@/config/myConfiguration.js'
import { getImageUrlWithDomain } from '@/utils/imageUtil.js'
import { saveOrUpdateDriverReview, getReviewById } from '@/api/user.js'
import { useUserStore } from '@/stores/userStore.js'
import { 
	genderEnum, getGenderNameByCode, getGenderCodeByName, 
	driverCarTypeEnum, getDriverCarNameByCode, getDriverCarCodeByName,
	auditStatusEnum
} from '@/utils/enums.js'

const driver = useUserStore()

// 是否只读
const readOnly = ref(false)

// 表单数据
const formData = ref({
	// 基本信息
	profileImg: null,
	surname: null,
	name: null,
	sex: null,
	phone: driver.getCurrentDriver().phone,
	// 身份证
	idCard: null,
	idCardFrontImg: null,
	idCardBackImg: null,
	// 紧急联系人
	emergencyContact: null,
	emergencyContactPhone: null,
	// 驾照信息
	driverCardFrontImg: null,
	driverCardBackImg: null,
	driverCardReceiveTime: null,
	driverCardExpriesTime: null,
	driverAge: null,
	driverCarType: null,
	auditStatus: auditStatusEnum.PENDING.value,
	// 银行卡
	bankName: null,
	bankCardId: null
	
	/* // 基本信息
	profileImg: null,
	surname: '蔡',
	name: '徐坤',
	sex: 0,
	phone: '13512345678',
	// 身份证
	idCard: '440923199808021234',
	idCardFrontImg: null,
	idCardBackImg: null,
	// 紧急联系人
	emergencyContact: '陈立农',
	emergencyContactPhone: '13712345678',
	// 驾照信息
	driverCardFrontImg: null,
	driverCardBackImg: null,
	driverCardReceiveTime: '2025-08-08',
	driverCardExpriesTime: '2025-08-08',
	driverAge: 3,
	driverCarType: 1,
	auditStatus: auditStatusEnum.PENDING.value */
})

// 可选性别
const sexOptions = Object.keys(genderEnum).map(k => genderEnum[k].label)
// 可选驾驶证类型
const driverTypeOptions = Object.keys(driverCarTypeEnum).map(k => driverCarTypeEnum[k].label)

// 图片选择
function chooseImage (field) {
	if (readOnly.value) {
		const imgs = []
		Object.keys(formData.value).forEach(k => {
			// 判断是否是图片
			if (typeof formData.value[k] === 'string' && formData.value[k].includes(FILE_PREFIX)) {
				imgs.push(formData.value[k])
			}
		})
		if (imgs.length > 0) {
			uni.previewImage({
				urls: imgs,
				current: imgs.indexOf(formData.value[field])
			})
		}
		
	} else {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				formData.value[field] = res.tempFilePaths[0]
			}
		})
	}
	
}
// 切换性别
function onChangeSex (e) {
	const name = sexOptions[e.detail.value]
	formData.value.sex = getGenderCodeByName(name)
}
// 切换准驾车型
function onChangeDriverCarType (e) {
	const name = driverTypeOptions[e.detail.value]
	formData.value.driverCarType = getDriverCarCodeByName(name)
}

// 必填字段
const requiredFields = {
	// 基本信息
	// profileImg: '请上传头像',
	surname: '请输入您的姓氏',
	name: '请输入您的名称',
	sex: '请选择您的性别',
	phone: '请输入您的手机号',
	// 身份证
	idCard: '请输入您的身份证号',
	idCardFrontImg: '请上传您的身份证正面照',
	idCardBackImg: '请上传您的身份证反面照',
	// 紧急联系人
	emergencyContact: '请输入紧急联系人姓名',
	emergencyContactPhone: '请输入紧急联系人电话',
	// 驾照信息
	driverCardFrontImg: '请上传您的驾驶证正面照',
	driverCardBackImg: '请上传您的驾驶证反面照',
	driverCardReceiveTime: '请输入您的驾驶证获取时间',
	driverCardExpriesTime: '请输入您的驾驶证过期时间',
	driverAge: '请输入您的驾龄',
	driverCarType: '请选择您的准驾车型',
	// 银行卡
	bankName: '请输入您的开户银行',
	bankCardId: '请输入银行卡号'
}
// 格式校验字段
const regexFields = {
	phone: {
		regex: /^1[3-9]\d{9}$/,
		text: '手机号格式错误'
	},
	idCard: {
		regex: /^\d{6}((((((19|20)\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(((19|20)\d{2})(0[13578]|1[02])31)|((19|20)\d{2})02(0[1-9]|1\d|2[0-8])|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))0229))\d{3})|((((\d{2})(0[13-9]|1[012])(0[1-9]|[12]\d|30))|((\d{2})(0[13578]|1[02])31)|((\d{2})02(0[1-9]|1\d|2[0-8]))|(([13579][26]|[2468][048]|0[048])0229))\d{2}))(\d|X|x)$/,
		text: '身份号格式错误'
	},
	emergencyContactPhone: {
		regex: /^1[3-9]\d{9}$/,
		text: '紧急联系人手机号格式错误'
	}
}
// 提交前校验
function validate () {
	// 非空判断
	const keys1 = Object.keys(requiredFields)
	for (const k of keys1) {
		if (formData.value[k] === null || formData.value[k] === undefined) {
			uni.showToast({
				title: `${requiredFields[k]}`,
				icon: 'none'
			})
			return false
		}
	}
	// 格式校验
	const keys2 = Object.keys(regexFields)
	for (const k of keys2) {
		if (!regexFields[k].regex.test(formData.value[k])) {
			uni.showToast({
				title: `${regexFields[k].text}`,
				icon: 'none'
			})
			return false
		}
	}
	return true
}
// 批量上传图片
function uploadImageBatch () {
	const needUploadsFields = [ 'profileImg', 'idCardFrontImg', 'idCardBackImg', 'driverCardFrontImg', 'driverCardBackImg' ]
	return needUploadsFields.map(field => {
		return new Promise((resolve, reject) => {
			if (!formData.value[field]) {
				// 未选择图片
				resolve(null)
			} else if (formData.value[field].includes('/profile')) {
				// 未做修改
				resolve(formData.value[field])
			} else if (formData.value[field]) {
				// 选择了新图片
				apiUpload(formData.value[field]).then(res => {
					const data = JSON.parse(res.data)
					const imgUrl = data.data
					formData.value[field] = imgUrl
					resolve(imgUrl)
				}).catch(err => {
					reject(err)
				})
			}
		})
	})
}
// 表单提交
function handleSubmit () {
	// 校验
	if (!validate()) return
	
	// 加载
	uni.showLoading({
		title: '正在提交资料，请稍候',
		mask: true
	})
	// 上传图片
	const tasks = uploadImageBatch()
	// 等待图片全部上传
	Promise.all(tasks).then(res => {
		formData.value['driverId'] = driver.getCurrentDriver().id
		// console.log(formData.value)
		saveOrUpdateDriverReview(formData.value).then(resp => {
			uni.hideLoading()
			uni.$emit('reviews-change')
			
			// 判断当前是否只有1页
			if (getCurrentPages().length === 1) {
				uni.reLaunch({
					url: '/pages/index/index',
					success: () => {
						uni.showToast({
							title: '审核资料上传成功',
							icon: 'none',
							mask: true
						})
					}
				})
			} else {
				uni.navigateBack({
					success: () => {
						success: () => {
							uni.showToast({
								title: '审核资料上传成功',
								icon: 'none',
								mask: true
							})
						}
					}
				})
			}
			
		}).catch(err => {
			uni.hideLoading()
		})
	}).catch(err => {
		uni.hideLoading()
		uni.showToast({
			title: '审核资料上传失败，请重新进入此页面',
			icon: 'none'
		})
	})
}

// 跳过认证--->到首页
function handleJump() {
	uni.reLaunch({
		url: '/pages/index/index'
	})
}

onLoad(e => {
	// 是否只读
	if (e.readOnly) {
		readOnly.value = JSON.parse(e.readOnly)
	}
	// 查询
	if (e.id) {
		uni.showLoading({
			title: '加载中...',
			mask: true
		})
		getReviewById(e.id).then(res => {
			// 图片前缀
			Object.keys(res.data).forEach(k => {
				if (typeof res.data[k] === 'string' && res.data[k].includes('/profile')) {
					res.data[k] = getImageUrlWithDomain(res.data[k])
				}
			})
			formData.value = res.data
		}).finally(e => {
			uni.hideLoading()
		})
	}
})

</script>

<style lang="scss" scoped>
view, picker {
	box-sizing: border-box;
}

.container {
	padding: 24rpx;
	background-color: #f8f8f8;
	min-height: 100vh;
	
	.jump-container {
		display: flex;
		justify-content: flex-end;
		margin-bottom: 16rpx;
		.jump {
			font-size: 28rpx;
			color: #007aff;
		}
	}
	
	.section {
		margin-bottom: 32rpx;
		background: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
	
		&-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 24rpx;
			display: block;
			padding-bottom: 16rpx;
			border-bottom: 1rpx solid #eee;
		}
		
		.form-group {
			margin-bottom: 24rpx;
		
			&:last-child {
				margin-bottom: 0;
			}
			
			.form-label {
				font-size: 28rpx;
				color: #666;
				margin-bottom: 12rpx;
				display: block;
			
				&.required::after {
					content: '*';
					color: #f56c6c;
					margin-left: 4rpx;
				}
			}
			
			.upload-wrapper {
				width: 100%;
				min-height: 200rpx;
				border-radius: 12rpx;
				background: #f9f9f9;
				display: flex;
				justify-content: center;
				align-items: center;
				border: 1rpx dashed #ddd;
				
				.upload-image {
					width: 100%;
					min-height: 200rpx;
					border-radius: 12rpx;
					image {
						width: 100%;
						height: 100%;
					}
				}
				
				.upload-placeholder {
					display: flex;
					flex-direction: column;
					align-items: center;
					color: #999;
					font-size: 24rpx;
				
					text {
						margin-top: 12rpx;
					}
				}
				
			}
			
			.form-input {
				height: 88rpx;
				padding: 0 24rpx;
				background: #f9f9f9;
				border-radius: 12rpx;
				font-size: 28rpx;
				border: 1rpx solid #eee;
			}
			
			.form-picker {
				width: 100%;
				height: 88rpx;
				padding: 0 24rpx;
				background: #f9f9f9;
				border-radius: 12rpx;
				font-size: 28rpx;
				border: 1rpx solid #eee;
				display: flex;
				
				.picker-content {
					background: #f9f9f9;
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: space-between;
					.please-choose {
						color: #888;
					}
				}
				
			}
			
		}
		
	}
	
	.submit-btn {
		margin-top: 48rpx;
		height: 96rpx;
		line-height: 96rpx;
		border-radius: 48rpx;
		font-size: 32rpx;
		background: linear-gradient(90deg, #2979ff, #00b0ff);
		color: #fff;
		border: none;
	
		&::after {
			border: none;
		}
	}
	
}
</style>